<template>
	<view class="uni-container">
		<uni-forms ref="form" :value="formData" validateTrigger="bind">
			<uni-forms-item name="types" label="收款方式">
				<uni-data-checkbox :multiple="true" v-model="formData.types" collection="tian-payment-types"
					field="payment_id as value,title as text" orderby="posid asc" where="state==1"
					@change="changePayment" />
			</uni-forms-item>

			<uni-forms-item name="payments" label="支付配置" v-if="formData.payments && formData.payments.length>0">
				<view class="items" v-for="(pay,index1) in formData.payments" :key="index1">
					<uni-forms :ref="'form'+index1" :value="pay" validateTrigger="bind">
						<view class="">
							<text>{{pay.title}}配置</text>
							<text class="colorGray">(不填写将使用默认配置)</text>
						</view>
						<uni-forms-item v-for="(item,index) in pay.attributes" :name="index" :key="index"
							:label="item.title" labelWidth="90">
							<block v-if="item.enum">
								<uni-data-checkbox v-if="item.enum.collection" v-model="item.value"
									:collection="item.enum.collection" :field="item.enum.field" />
								<uni-data-checkbox v-else v-model="item.value" :localdata="item.enum" />
							</block>
							<uni-easyinput v-else-if="item.bsonType=='int'" type="number" v-model="item.value" />
							<uni-easyinput v-else-if="item.bsonType=='string'" v-model="item.value" />
							<switch v-else-if="item.bsonType=='bool'" @change="binddata('state', $event.detail.value)"
								:checked="!!item.value" />
						</uni-forms-item>
					</uni-forms>
				</view>
			</uni-forms-item>
			<uni-forms-item name="rebate_rate" label="返红包比例">
				<uni-easyinput placeholder="请输入返红包比例,0-1000" type="number" v-model="formData.rebate_rate" />
			</uni-forms-item>
			<uni-forms-item name="money_rate" label="佣金比例">
				<uni-easyinput placeholder="请输入佣金比例,0-1000" type="number" v-model="formData.money_rate" />
			</uni-forms-item>
			<uni-forms-item name="background" label="收款背景">
				<cloud-image name="background" v-model="formData.background" />
			</uni-forms-item>
			<uni-forms-item name="payment_notice" label="支付公告">
				<uni-easyinput placeholder="请输入收款页面公告" type="textarea" v-model="formData.payment_notice" />
			</uni-forms-item>


			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'tian-mall-shops';

	export default {
		data() {
			return {
				formData: {
					"rebate_rate": 5,
					"money_rate": 5,
					"background": "",
					"payment_notice": "",
					"types": [],
					"payments": []
				},
				formOptions: {
					paymentTypes: {}
				},
				rules: {
					"types": {
						"rules": [{
							"format": "array"
						}]
					},
					"rebate_rate": {
						label: "返红包比例",
						"rules": [{
							"format": "int"
						}, {
							minimum: 0,
						}, {
							maximum: 1000,
						}]
					},
					"money_rate": {
						label: "佣金比例",
						"rules": [{
							"format": "int"
						}, {
							minimum: 0,
						}, {
							maximum: 1000,
						}]
					},
				}
			}
		},
		onLoad(e) {
			const id = e.id
			this.formDataId = id
			this.getDetail(id)
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			/**
			 * 触发表单提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.submit().then((res) => {
					console.log("res", res)
					//统计payment值
					let payments = {}
					res.payments.map(pay => {
						let data = {};
						for (let key in pay.attributes) {
							if (pay.attributes[key].value) {
								data[key] = pay.attributes[key].value;
							}
						}
						payments[pay.payment_id] = data
					});
					res.payments = payments;
					console.log("res", res)
					this.submitForm({
						qr_code_payment: res
					})
				}).catch((errors) => {
					uni.hideLoading()
				})
			},

			submitForm(value) {
				// 使用 clientDB 提交数据
				db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field(
					'qr_code_payment'
				).get().then((res) => {
					const data = res.result.data[0]
					if (data && data.qr_code_payment) {
						this.formData = data.qr_code_payment
					}
					this.getPaymentTypes((extIds) => {
						this.changePayment({
							detail: {
								value: this.formData.types
							}
						})
					});
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			getPaymentTypes(callback) {
				db.collection("tian-payment-types").where("state==1").orderBy("posid asc").get().then(({
					result
				}) => {
					console.log("result", result)
					let extIds = []
					result.data.forEach(item => {
						if (this.formData.payments[item.payment_id]) {
							let val = this.formData.payments[item.payment_id];
							for (let key in item.attributes) {
								item.attributes[key].value = val[key] ? val[key] : "";
							}
							extIds.push(item.payment_id);
						} else {
							for (let key in item.attributes) {
								item.attributes[key].value = "";
							}
						}
					})
					this.formOptions.paymentTypes = result.data;
					if (callback) {
						callback(extIds)
					}
				})
			},
			changePayment(e) {
				console.log("changePayment", e)
				if (e.detail.value.length == 0) {
					this.formData.payments = []
					return;
				}
				this.formData.payments = this.formOptions.paymentTypes.filter(item => e.detail.value.indexOf(item
						.payment_id) !=
					-1)

				console.log("this.formData.payments", this.formData.payments)
			}
		}
	}
</script>

<style lang="scss">
	.items {
		padding: 20rpx;
		border-radius: 20rpx;
	}
</style>
